package gl.drawer

import gl.util.GLUtils
import gl.window
import org.lwjgl.opengl.GL30C
import org.lwjgl.opengl.GL33C
import org.lwjgl.opengl.GL46C.*

class Framebuffer: Drawer() {

    // 0: color, 1: depth
    private val renderbuffers = IntArray(2)
    private var framebuffer = 0

    override fun initialize() {
        // framebuffer
        framebuffer = glGenFramebuffers()
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer)
        glGenRenderbuffers(renderbuffers)
        glBindRenderbuffer(GL_RENDERBUFFER, renderbuffers[0])
        glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA4, 256, 256)
        glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffers[0])
        glBindRenderbuffer(GL_RENDERBUFFER, renderbuffers[1])
        glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, 256, 256)
        glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, renderbuffers[1])

        glEnable(GL_DEPTH_TEST)
    }

    override fun update(): Boolean {
        // 渲染到帧缓存
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer)
        glViewport(0, 0, 256, 256)
        glClearColor(1f, 0f, 0f, 1f)
        glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)
        // 拷贝到窗口系统缓存
        glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer)
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)
        glViewport(0, 0, window.width, window.height)
        glClearColor(0f, 0f, 1f, 1f)
        glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)
        glBlitFramebuffer(0, 0, 255, 255, 0, 0, 255, 255, GL_COLOR_BUFFER_BIT, GL_NEAREST)
        GLUtils.capture()
        return false
    }

    override fun terminal() {
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)
        glBindFramebuffer(GL_READ_FRAMEBUFFER, 0)
        glDeleteFramebuffers(framebuffer)
        glDeleteRenderbuffers(renderbuffers)
    }
}